package zoo.reviewboard.user.controller;

import java.io.File;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import zoo.reviewboard.user.dao.ProductReviewBoardDao;
import zoo.reviewboard.user.domain.ProductReviewBoardCommand;
import zoo.reviewboard.user.validator.ProReviewValidator;
import zoo.util.FileUtil;

@Controller
public class ProductReviewBoardInsertController {
		
	@Autowired
	private ProductReviewBoardDao dao;
	private String formView = "review_product"; 
	
	@RequestMapping(value="/main/writeReivew.do", method=RequestMethod.GET)
	public ModelAndView form(@RequestParam("p_code") int p_code){
		return new ModelAndView(formView,"p_code",p_code);
	}
	
	@ModelAttribute("reviewCommand")
	public ProductReviewBoardCommand formBacking() {
		return new ProductReviewBoardCommand();
	}
	
	@RequestMapping(value="/main/writeReivew.do", method=RequestMethod.POST)
	public String submit(@ModelAttribute("reviewCommand")ProductReviewBoardCommand Command,@RequestParam("p_code") int p_code){

		String formView2 = "redirect:/main/detailPro.do?p_code="+p_code+"#2";
				
		String path = "D:/javaWork/workspace-spring/urkr/WebContent/amemberUpload";
		
		try {
			String newName = "";
			if(!Command.getUpload().isEmpty()){
				newName = FileUtil.rename(Command.getUpload().getOriginalFilename());
				Command.setPr_image(newName);
			}
			dao.insertReview(Command);
			
			if(!Command.getUpload().isEmpty()){
				File file = new File(path + "/" + newName);
				Command.getUpload().transferTo(file);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return formView2;
	}

}
